/*
 * spi.c
 *
 * Created: 2012/5/19 21:09:18
 *  Author: albert
 */ 

#include "spi.h"

unsigned char spi_buff[spi_buff_size];
volatile unsigned char spi_count=0;

void SPI_MasterInit (void)
{
	/* set MOSI and SCK output, all others input */
	DDR_SPI =(1<<DD_MOSI)|(1<<DD_SCK)|(1<<DD_SS);
	/* Enable SPI, Master, set clock rate fck/4 */
	SPCR= (1<<SPE)|(1<<MSTR)|(1<<SPR1)|(1<<SPR0);
	//Interrupt enable
	//SPCR= (1<<SPE)|(1<<MSTR)|(1<<SPIE);
}

void SPI_SlaveInit (void)
{
	/* set MISO output, all others input */
	DDR_SPI =(1<<DD_MISO);
	/* Enable SPI*/
	//SPCR= (1<<SPE);
	//Interrupt enable
	SPCR= (1<<SPE)|(1<<SPIE);
}

void SPI_MasterTransmit(char data)
{
	/* start transmission */
	SPDR=data;
	/* wait for transmission complete */
	while (!(SPSR&(1<<SPIF)))
	;
}

char SPI_SlaveReceive(void)
{
	/* wait for reception complete */
	while (!(SPSR&(1<<SPIF)))
	;
	return SPDR;
}

/********************************************************
 *                                                                                                                          *
 * INTERRUPT                                                                                                   *
 * |better! NO function calls in the interrupt|                                       *
 ********************************************************/
ISR(SPI_STC_vect)
{
	 //spi_buff[spi_count++] = SPDR; 
	 PORTC = SPDR;
}